package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import server.GetTrackIp;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

@SuppressWarnings("serial")
public class IpServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		
		String path = ((HttpServletRequest)req).getRequestURI();
		
		String page = req.getParameter("p");
		int p = Paginate.page(page);
		int limit = 10;
		int start = (p-1)*limit;
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        	
        }
		st.nextToken();
		String name = st.nextToken();
		if(name!=null&&name.length()>0&&Pattern.matches("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$", name))
		{
			DBCollection coll = Data.data("domain");
			DBCollection collection = Data.data("ip");
	
			DBCursor domain = coll.find(new BasicDBObject("ip",name)).skip(start).limit(limit);
	
			if(domain != null && domain.size() > 0)
			{
				resp.setHeader( "Cache-Control", "public, max-age=86400");
				resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
				@SuppressWarnings({ "unchecked"})
				ArrayList<String> lastPing = (ArrayList<String>)Utils.cache.get("last-ip");
	        	
	        	
	        	if(lastPing != null && lastPing.size() > 0)
	        	{
		        	if(lastPing.size()>19)
		        	{
		        		lastPing.remove(0);
		        	}
		        	int check = 0;
		        	for (int i = 0; i < lastPing.size(); i++) {
						if(lastPing.get(i).equals(name))
						{
							check = 1;
						}
					}
		        	if(check == 0)
		        		lastPing.add(name);
		        		Utils.cache.put("last-ip", lastPing);
	        	} else {
	        		ArrayList<String> lastPings =  new ArrayList<String>();
	        		lastPings.add(name);
	        		Utils.cache.put("last-ip", lastPings);
	        	}
				
				int total = coll.find(new BasicDBObject("ip",name)).count();
				
				int np = (total%limit == 0)?total/limit:total/limit+1;
				
				DBObject dbObject = collection.findOne(new BasicDBObject("name",name));
				if(dbObject==null)
				{
					try {
						new GetTrackIp(name);
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				dbObject = collection.findOne(new BasicDBObject("name",name));
				if(dbObject==null)
				{
					dbObject = new BasicDBObject();
				}
				req.setAttribute("dbObject", dbObject);
				
				req.setAttribute("domain", domain);
				req.setAttribute("name", name);
				req.setAttribute("total", String.valueOf(total));
				req.setAttribute("page", String.valueOf(p));
				req.setAttribute("np", String.valueOf(np));
				req.setAttribute("path", "?");
				
				DBObject wip = coll.findOne(new BasicDBObject("ip",name));
				req.setAttribute("wip", wip);
				
				try {
					req.getRequestDispatcher("/ip.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} 
		} else {
			resp.getWriter().println("Hello, world");
		}
	}

}
